#!/usr/bin/ruby
$:.unshift File.join(File.dirname(__FILE__))
require 'AWS/S3'
require 'basic_configuration'
require 'aws_context'
require 'pp'

#  Retrieves the metadata of an S3 object (key).
# The bucket may be supplied on the command line or in the environment.

if ARGV[0] == '-?' || ARGV.size < 1 then
  puts "usage: list-object-metadata key [bucket]"
  exit 1
end
key=ARGV[0]
if ARGV.size >= 2
  bucket = ARGV[1]
end

config = BasicConfiguration.new
bucket = config.aws[:aws_bucket] unless bucket
if bucket.nil?
  puts "AWS_BUCKET environment variable must be set or defined in config file."
  exit 1
end

Signal.trap("INT") do
  exit 2
end

s3 = AwsContext.instance.s3(*config.keys)
begin
  res = s3.get_object_metadata(bucket, key)
  res[:metadata].each do |k, v|
    STDOUT.puts("#{k}\t#{v}")
  end
rescue
  puts "error: #{$!} -- not listed"
  exit 1
end
